package com.novel.base.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.*;
import com.novel.authorization.tenant.CustomTenantHandler;
import com.novel.authorization.vip.CustomVipHandler;
import com.novel.authorization.vip.VipInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 分页插件
 *
 * @author zc
 */
@Configuration
@MapperScan({"com.*.*.*.mapper", "com.*.*.mapper"})
public class MybatisPlusConfig {
    private CustomTenantHandler customTenantHandler;
    private CustomVipHandler customVipHandler;

    @Autowired
    public void setCustomTenantHandler(CustomTenantHandler customTenantHandler) {
        this.customTenantHandler = customTenantHandler;
    }

    @Autowired
    public void setCustomVipHandler(CustomVipHandler customVipHandler) {
        this.customVipHandler = customVipHandler;
    }

    @Value("${custom.tenant.enable}")
    private boolean tenantEnable;
    @Value("${custom.vip.enable}")
    private boolean vipEnable;

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        // 多租户拦截
        if (tenantEnable) {
            TenantLineInnerInterceptor tenantInterceptor = new TenantLineInnerInterceptor();
            tenantInterceptor.setTenantLineHandler(customTenantHandler);
            interceptor.addInnerInterceptor(tenantInterceptor);
        }
        // Vip等级拦截
        if (vipEnable) {
            VipInnerInterceptor vipInnerInterceptor = new VipInnerInterceptor();
            vipInnerInterceptor.setCustomVipHandler(customVipHandler);
            interceptor.addInnerInterceptor(vipInnerInterceptor);
        }
        // 添加非法SQL拦截器
//        interceptor.addInnerInterceptor(new IllegalSQLInnerInterceptor());

        DataChangeRecorderInnerInterceptor dataChangeRecorderInnerInterceptor =
                new DataChangeRecorderInnerInterceptor();
        // 配置安全阈值，限制批量更新或删除的记录数不超过 1000 条
        dataChangeRecorderInnerInterceptor.setBatchUpdateLimit(1000).openBatchUpdateLimitation();
        interceptor.addInnerInterceptor(dataChangeRecorderInnerInterceptor);

        // 乐观锁
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

        // 防止全表更新与删除
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());

        // 如果配置多个插件, 切记分页最后添加
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

        return interceptor;
    }

}